package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class IMService {

    @DubboReference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private UsersApi usersApi;

    @DubboReference(version = "1.0.0")
    private MessageApi messageApi;

    @DubboReference(version = "1.0.0")
    private MyCenterApi myCenterApi;

    public UserInfoVo queryUserInfoByUserName(String userName) {
        //根据环信用户名查询用户id
        HuanXinUser huanXinUser = this.huanXinApi.queryHuanXinUserByUserName(userName);

        //根据用户id查询用户信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(huanXinUser.getUserId());

        //封装UserInfoVo
        UserInfoVo userInfoVo = BeanUtil.toBeanIgnoreError(userInfo, UserInfoVo.class);
        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    /**
     * 添加联系人
     *
     * @param userId
     * @return
     */
    public Object addContacts(Long userId) {
        //注册好友关系到MongoDB
        String result = this.usersApi.saveUsers(UserThreadLocal.get(), userId);
        if (StrUtil.isNotEmpty(result)) {
            //注册好友关系到环信
            Boolean bool = this.huanXinApi.addUserFriend(UserThreadLocal.get(), userId);
            if (bool) {
                return null;
            }
        }
        return ErrorResult.builder().errCode("500").errMessage("添加好友失败！").build();
    }

    /**
     * 查询联系人列表
     *
     * @param page
     * @param pageSize
     * @param keyword  根据关键字搜索
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();
        List<UserInfo> userInfoList;
        if (StrUtil.isEmpty(keyword)) {
            //按顺序查询，按照添加时间倒序排序
            PageInfo<Users> pageInfo = this.usersApi.queryUsersList(userId, page, pageSize);
            List<Users> records = pageInfo.getRecords();
            if (CollUtil.isEmpty(records)) {
                return pageResult;
            }
            //获取用户信息列表
            //TODO 按照Records列表中的顺序进行输出 --完成
            userInfoList = this.userInfoApi.queryByUserIdList(CollUtil.getFieldValues(records, "friendId"));
            //--完成上述的TODO
            List<UserInfo> userInfos=new ArrayList<>();
            for (Users users : records) {
                for (UserInfo userInfo : userInfoList) {
                    if (ObjectUtil.equal(users.getFriendId(),userInfo.getUserId())){
                        userInfos.add(userInfo);
                        break;
                    }
                }
            }
            //把排好序的集合复制到原本集合
            userInfoList=userInfos;
        } else {
            // 把所有的联系人查询出来，再进行筛选
            List<Users> usersList = this.usersApi.queryAllUsersList(userId);
            if (CollUtil.isEmpty(usersList)) {
                return pageResult;
            }
            List<Object> friendIdList = CollUtil.getFieldValues(usersList, "friendId");
            userInfoList = this.userInfoApi.queryListLikeNickName(friendIdList, keyword);

        }

        List<UsersVo> result = new ArrayList<>();

        //封装UsersVo
        for (UserInfo userInfo : userInfoList) {
            UsersVo usersVo = BeanUtil.toBeanIgnoreError(userInfo, UsersVo.class);
            usersVo.setUserId("HX_" + userInfo.getUserId());
            usersVo.setGender(userInfo.getSex().name().toLowerCase());
            usersVo.setCity(StrUtil.subBefore(userInfo.getCity(), '-', false));
            result.add(usersVo);
        }

        pageResult.setItems(result);
        return pageResult;
    }


    //com.tanhua.server.service.IMService

    /**
     * 删除好友
     *
     * @param userId 好友id
     */
    public void removeUser(Long userId) {
        //删除好友关系
        Long MyId= UserThreadLocal.get();
        Boolean result = this.usersApi.removeUsers(MyId, userId);
        if(result){
            //将环信平台的好友关系解除
            this.huanXinApi.removeUserFriend(MyId, userId);
        }
    }


    //查询点赞/喜欢/评论列表
    public PageResult queryCommentListByType(Integer page, Integer pageSize, CommentType type) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //调用api方法查comment表
        List<Comment> likesList = this.messageApi.queryCommentListByType(UserThreadLocal.get(),page, pageSize, type.getType());

        //无数据直接返回
        if (likesList.isEmpty()){
            return pageResult;
        }
        //有数据封装成OperationMessageVo类型

        //点赞人id集合
        List<Object> userIdList = CollUtil.getFieldValues(likesList, "userId");
        //点赞记录主键id集合
        List<Object> idList = CollUtil.getFieldValues(likesList, "id");
        //用id获取点赞用户信息集合
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);

        //定义个集合用于返回数据
        ArrayList<OperationMessageVo> messageVoList = new ArrayList<>();

        for (int index = 0; index < userInfoList.size() - 1; index++) {
            //将数据封装进messageVoList
            OperationMessageVo operationMessageVo = new OperationMessageVo();
            operationMessageVo.setId(idList.get(index).toString());
            operationMessageVo.setAvatar(userInfoList.get(index).getLogo());
            operationMessageVo.setNickname(userInfoList.get(index).getNickName());

            Long created = likesList.get(index).getCreated();
            String createdFormat = DateUtil.format(new Date(created), "yyyy-MM-dd HH:mm");
            operationMessageVo.setCreateDate(createdFormat);

            messageVoList.add(operationMessageVo);
        }

        //封装进PageResult返回
        pageResult.setItems(messageVoList);
        return pageResult;
    }


    //查询公告列表
    public PageResult queryAnnouncementsList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //调用方法获取公告列表

        IPage<Announcement> announcementIPage = null;
        try {
            announcementIPage = this.myCenterApi.queryAnnouncementsList(page, pageSize);
        } catch (Exception e) {
            log.error("查询公告表失败，error:{}",e);
        }

        List<Announcement> announcementList = announcementIPage.getRecords();

        //字段名不同不能直接返回，封装到vo对象
        ArrayList<AnnouncementVo> announcementVoArrayList = new ArrayList<>();
        for (Announcement announcement : announcementList) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(Convert.toStr(announcement.getId()));
            announcementVo.setDescription(announcement.getDescription());
            announcementVo.setTitle(announcement.getTitle());
            announcementVo.setCreateDate(DateUtil.format(announcement.getCreated(),"yyyy-MM-dd HH:mm"));

            announcementVoArrayList.add(announcementVo);
        }

        if (announcementList.isEmpty()){
            return pageResult;
        }

        pageResult.setItems(announcementVoArrayList);

        return pageResult;
    }
}
